<template>
  <section id="pubDynamic">
      <ma-header titleName='发动态' class="header">
          <div slot="title-right" class="title-right" :class="{isSubmit:!isSilent&&isSubmit&&isContentSubmit}" @click="submit">发布</div>
      </ma-header>
      <div class="dynamic-title" v-if="!isFromTopic">
          <textarea v-model="title" placeholder="加个标题哦" type="text" autofocus="autofocus"></textarea>
      </div>
      <div class="dynamic-content" id="dynamic-content">
          <VuePellEditor
            :actions="editorOptions" 
            :content="editorContent" 
            :placeholder="editorPlaceholder"
            v-model="editorContent"
            :styleWithCss="false"
            :classes="editorClasses"
            @change="doSomething"/>

        <div class="content-icon">
          <i class="iconfont icon-biaoqing" v-tap="{methods: Expression}"></i>
          <i class="iconfont icon-tupian" v-tap="{methods: upload}"></i>
            <!-- <img  v-tap="{methods: Expression}" src="../../assets/icon_fav.png" height="40%" width="40%">
            <img  v-tap="{methods: upload}" src="../../assets/add-img.png" height="40%" width="40%"> -->
        </div>
      </div>
      <div class="emojiBox">
          <emoji v-if="showEmoji" v-on:emojiDoc='emojiDoc'/>
      </div>
        
  </section>
</template>
<script>
import maHeader from "components/magicHeader";
import VuePellEditor from "vue-pell-editor";
import emoji from "components/emojiNew";
import CreateSpaceService from "services/community/CreateSpace";
import QueryStore from "services/community/QueryStore";
import emojiService from "services/common/emoji";
let EMOJI_OBJ = emojiService.EMOJI_MAP
const MAX_IMAGE_COUNT = 9;

/**
 * @description 上传选中的图片到服务器
 * @augments promises 请求方法
 * @augments evalProductImage view-model
 * @augments resp 本地缓存
 * @argument vm Vue instance
 */
function upload2Server(promises, resp, vm) {
  Promise.all(promises).then(
    results => {
      let promiseResult = results.every(result => {
        return result.urls && result.resultCode === "100";
      });

      // 如果图片上传成功 就将之前缓存的图片
      if (promiseResult) {
        resp.forEach(val => {
          if (vm.nativeImages.length < MAX_IMAGE_COUNT) {
            vm.nativeImages.push(val);
          }
        });
        results.forEach(result => {
          //   vm.imgUrls.push(...result.urls);
          result.urls.forEach(url => {
            url = vm.$.host + url;
            window.pell.exec("insertImage", url);
          });
        });
      } else {
        vm.$.toast("上传图片失败");
      }
    },
    err => {
      if (err) {
        vm.$.toast("上传图片失败");
      }
    }
  );
}
export default {
  name: "pubDynamic",
  components: {
    maHeader,
    VuePellEditor,
    emoji
  },
  data() {
    return {
      editorOptions: [
        // 富文本的提示框  使用class 隐藏了  如果删除会全部显示
        {
          name: "image",
          result: () => {
            const url = window.prompt("Enter the image URL");
            if (url) window.pell.exec("insertImage", url);
          }
        }
      ],
      editorPlaceholder: "分享新鲜事", // Placeholder
      editorContent: "", // 显示的内容
      editorClasses: {
        // 添加 class 名
        actionbar: "pell-actionbar-custom-name",
        button: "pell-button-custom-name",
        content: "pell-content-custom-name"
      },
      title:'',  // 标题
      nativeImages: [], // 记录保存的图片
      showEmoji: false,
      isFromTopic:false,
      topicId:'',
      imgUrls:[],
      isSubmit:false,
      isContentSubmit:false,
      isSilent:false  // 社区被禁言
    };
  },
  created() {
    let params = this.$route.query
    this.getcommunitySilent()
    if(params.topicId){
      this.isFromTopic = true;
      this.isSubmit = true
      console.log(params)
      this.editorContent =`#${params.topicTitle}#`
      this.topicId = params.topicId
    }
  },
  watch:{
    title:function(newval){
      if(this.$.isEmpty(newval)){
        this.isSubmit = false
      }else{
        this.isSubmit = true
      }
    },
    editorContent:function(newval){
      if(this.$.isEmpty(newval)){
        this.isContentSubmit = false
      }else{
        this.isContentSubmit = true
      }
    }
  },
  methods: {
    getcommunitySilent(){
      QueryStore.bind(this)({

      },resp=>{
        console.log(resp.shop.communitySilent)
        this.isSilent = resp.shop.communitySilent === '1'? true : false
      })
    },
    submit() {
      if(this.isSilent){
        this.$.toast('您已被禁言')
        return
      }
      if(!this.isSubmit&&!isContentSubmit){
        return
      }
      let _editorContentNew  // 处理之后的数据
      let _saveContent = this.editorContent  // 待处理的数据
      let _host  = this.$.host
      let flag = true  // 是否跳出循环
      
      let indexStart = 0 // 记录查找位置
      let indexEnd = 0
      let vm = this
      while (flag) {
        if(_saveContent.indexOf('<img',indexStart)=== -1){
          flag = false
        }else{
          indexStart= _saveContent.indexOf('<img',indexStart)
          indexEnd = _saveContent.indexOf('>',indexEnd)
          let strDel =_saveContent.slice(indexStart,indexEnd + 1)
          if(strDel.indexOf('class="emoji"')>-1){
            let _emoji = strDel.split('emoji/')[1].split('.png">')[0]
            for (let k in EMOJI_OBJ){
              if(EMOJI_OBJ[k] === _emoji){
                _saveContent = _saveContent.split(strDel).join(k)
              }
            }
          }else{
            let url = strDel.split('src="')[1].split('">')[0]
            console.log(url)
            this.imgUrls.push(url)
            indexStart ++;
            indexEnd ++
          }
        }
        
      }
      _editorContentNew = _saveContent.split(_host).join('')
      console.log(_editorContentNew);
      setTimeout(() => {
        CreateSpaceService.bind(vm)({
            content: _editorContentNew,
            title: vm.title,
            images: this.imgUrls,
            position: "",
            topics: vm.topicId ? [vm.topicId] : []
          },
          resp => {
            // 跳转回carFri_home
            vm.$.toast('发动态成功')
            vm.$router.go(-1);
          },
          (err, resultCode) => {
            vm.$.toast({
              message: err,
              duration: 1500
            });
        });
      }, 0);
    },
    doSomething() {
      console.log('hello')
    },
    /* 添加图片 */
    upload(params) {
      // 最多支持添加的图片数量
      if (this.nativeImages.length >= MAX_IMAGE_COUNT) {
        this.$.toast(`您最多可以添加${MAX_IMAGE_COUNT}张图片`);
        return;
      }

      // bridge, 选择相册中的图片
      this.$.push(
        "router_takePhoto",
        {
          maxNum: MAX_IMAGE_COUNT - this.nativeImages.length
        },
        resp => {
          resp = JSON.parse(resp);
          let promises = [];

          // 按type缓存图片地址
          let imgDataCache = new Map();
          resp.forEach(img => {
            promises.push(
              this.$.postFileByFormData({
                type: "." + img.type,
                data: [img.data]
              })
            );
          });

          // upload imgs 2 server
          promises.length > 0 && upload2Server(promises, resp, this);
        }
      );
    },
    // 添加表情
    Expression() {
      this.showEmoji = !this.showEmoji;
    },
    emojiDoc(val) {
      let str = this.emojiFilter(val)
      this.editorContent = this.editorContent + str;
      // 每次选择表情都关闭
      this.showEmoji = false
    },
     emojiFilter(content) {
      // test
      // content = "[:D]123[<//>]123awedasdasd";
      if (content) {
        for (let key in emojiService.EMOJI_MAP) {
          content = content.replace(key, function() {
            let src = emojiService.getEmojiSrc(key);
            return `<img class="emoji" width=22 src="${src}">`;
          });
        }
      }
      return content;
    },
  }
 
};
</script>
<style lang="scss">
#pubDynamic {
  .header {
    .title-right {
      font-size: 14px;
      color: #b9b9b9;
    }
    .title-right.isSubmit{
      color: #f98700
    }
  }
  textarea {
    width: 100%;
    border: none;
    // outline: none;
    padding: 10px;
    line-height: 24px;
    font-size: 16px;
    resize: none;
    overflow: auto;
  }
  .dynamic-title {
    width: 100%;
    textarea {
      height: 44px;
      padding-left: 15px;
    }
  }

  .dynamic-content {
    margin-top: 5px;
    background-color: #fff;
    // 富文本编辑器
    .pell-actionbar-custom-name {
      border-bottom: 5px solid #f8f8f8;
      button {
        display: none;  // 隐藏本身的选择按钮
        font-size: 18px;
      }
    }
    .pell-content-custom-name {
      border: none;
      min-height: 220px;
      font-size: 16px;
      padding: 10px 12px;
      img {
        width: 94%;
        margin: 5px 3%;
      }
      img.emoji {
        vertical-align: middle;
        width: 22px;
        margin: 0;
      }
    }
    .vp-editor__placeholder {
      padding: 5px;
      top: 10px;
      color: #939393;
      font-size: 16px;
      font-style: normal;
    }
    .content-icon {
      overflow: hidden;
      width: 20%;
      padding: 8px 0 3px 0;
      margin-right: 1.33%;
      display: flex;
      justify-content:space-around;
      .iconfont {
        font-size: 24px;
      }
    }
  }
  .emojiBox {
    position: fixed;
    background-color: #fff;
    bottom:0;
  }
}
</style>


